package cn.tedu.costservice.dao.repository.impl;

import cn.tedu.charging.common.util.JsonUtil;
import cn.tedu.costservice.dao.repository.CostRuleRedisRepository;
import cn.tedu.costservice.pojo.po.CostRulePO;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
@Slf4j
@Repository
public class CostRuleRedisRepositoryImpl implements CostRuleRedisRepository {
    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    /**
     * 查询计费标准
     * @param stationId
     * @return
     */
    @Override
    public List<CostRulePO> getCostRuleByStationId(Long stationId) {
        log.debug("查询redis的计费数据:{}",stationId);
        ValueOperations<String, Serializable> valueOperations = redisTemplate.opsForValue();
        String key="COST_RULE_"+stationId;
        Serializable serializable = valueOperations.get(key);
        log.debug("redis查询结果:{}",serializable);
        if (serializable!=null) {
            //TODO 序列化异常,但是能够返回结果,当时不会报错,后续会报LinkedHashMap不能转换成对象
            //return JsonUtil.fromJson(serializable.toString(),List.class);
            ObjectMapper objectMapper=new ObjectMapper();
            List<CostRulePO> list=new ArrayList<>();
            List<LinkedHashMap<String,CostRulePO>> maplist = JsonUtil.fromJson(serializable.toString(), List.class);
            for (LinkedHashMap<String,CostRulePO> map:maplist){
                CostRulePO costRulePO = objectMapper.convertValue(map, CostRulePO.class);
                list.add(costRulePO);
            }
            return list;
        }
        return null;
    }

    /**
     * 保存计费标准
     * @param stationId
     * @param costRulePO
     */
    @Override
    public void saveRule(Long stationId,List<CostRulePO> costRulePO) {
        log.debug("保存到redis中");
        ValueOperations<String, Serializable> valueOperations = redisTemplate.opsForValue();
        String key="COST_RULE_"+stationId;
        String value= JsonUtil.toJson(costRulePO);
        log.debug("普通字符串形式:{}",costRulePO.toString());
        log.debug("json格式:{}",value);
        valueOperations.set(key,value);
    }
}
